package com.yuexunit.mobilenurse.module.BloodManage.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodManage.bean.CheckDataBean;
import com.yuexunit.mobilenurse.module.BloodManage.model.impl.ReceiveModel;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.IReceivePresenter;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.impl.ReceivePresenter;
import com.yuexunit.mobilenurse.module.BloodManage.ui.fragment.Frag_Blood_Cancle_Idata;
import com.yuexunit.mobilenurse.module.BloodManage.ui.fragment.Frag_Blood_Receive;
import com.yuexunit.mobilenurse.module.BloodManage.ui.fragment.Frag_Blood_Record_Idata;
import com.yuexunit.mobilenurse.module.BloodManage.ui.fragment.Frag_Blood_Send_State_Idata;
import com.yuexunit.mobilenurse.module.BloodManage.ui.view.IReceiveView;
import com.yuexunit.mobilenurse.scan.Idata.ScannerInerface;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/11 0011.
 */

public class Act_Blood_Main_Idata extends KJActivity implements IReceiveView {
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.img_1)
    ImageView img_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.img_2)
    ImageView img_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.img_3)
    ImageView img_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
    @Bind(R.id.img_4)
    ImageView img_4;

    KJFragment mContentFragment;
    KJFragment fragment_1;
    KJFragment fragment_2;
    KJFragment fragment_3;
    KJFragment fragment_4;

    LoadingDialog dialog;
    IReceivePresenter presenter;

    ScannerInerface scanner;
    IntentFilter intentFilter;
    BroadcastReceiver scanReceiver;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_blood_main);
        ButterKnife.bind(this);
    }


    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(this);
        presenter = new ReceivePresenter(new ReceiveModel(), this);
        fragment_1 = new Frag_Blood_Receive();
        fragment_2 = new Frag_Blood_Send_State_Idata();
        fragment_3 = new Frag_Blood_Record_Idata();
        fragment_4 = new Frag_Blood_Cancle_Idata();

        mContentFragment = fragment_1;
        changeFragment(R.id.framelayout_content, mContentFragment);
    }

    @OnClick({R.id.back, R.id.rl_1, R.id.rl_2, R.id.rl_3, R.id.rl_4})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rl_1:
                tv_1.setTextColor(getResources().getColor(R.color.doc_advice_01));
                img_1.setBackgroundColor(getResources().getColor(R.color.doc_advice_01));
                tv_2.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_2.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_3.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_3.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_4.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_4.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                mContentFragment = fragment_1;
                changeFragment(R.id.framelayout_content, mContentFragment);
                break;
            case R.id.rl_2:
                tv_1.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_1.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_2.setTextColor(getResources().getColor(R.color.doc_advice_01));
                img_2.setBackgroundColor(getResources().getColor(R.color.doc_advice_01));
                tv_3.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_3.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_4.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_4.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                mContentFragment = fragment_2;
                changeFragment(R.id.framelayout_content, mContentFragment);
                break;
            case R.id.rl_3:
                tv_1.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_1.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_2.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_2.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_3.setTextColor(getResources().getColor(R.color.doc_advice_01));
                img_3.setBackgroundColor(getResources().getColor(R.color.doc_advice_01));
                tv_4.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_4.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                mContentFragment = fragment_3;
                changeFragment(R.id.framelayout_content, mContentFragment);
                break;
            case R.id.rl_4:
                tv_1.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_1.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_2.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_2.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_3.setTextColor(getResources().getColor(R.color.doc_advice_03));
                img_3.setBackgroundColor(getResources().getColor(R.color.doc_advice_05));
                tv_4.setTextColor(getResources().getColor(R.color.doc_advice_01));
                img_4.setBackgroundColor(getResources().getColor(R.color.doc_advice_01));
                mContentFragment = fragment_4;
                changeFragment(R.id.framelayout_content, mContentFragment);
                break;
        }
    }

    @Override
    public void onResume(){
        super.onResume();
        initScanner();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop(){
        super.onStop();
        finishScanner();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        finishScanner();
    }

    private void initScanner(){
        scanner = new ScannerInerface(this);
        scanner.open();	//打开扫描头上电   scanner.close();//打开扫描头下电
        scanner.enablePlayBeep(true);//是否允许蜂鸣反馈
        scanner.enableFailurePlayBeep(true);//扫描失败蜂鸣反馈
        scanner.enablePlayVibrate(true);//是否允许震动反馈
        scanner.setCharSetMode(4);//设置解码方式
        //		scanner.enablShowAPPIcon(false);//是否允许显示iscan的应用程序图标   部分设备 调用出现异常，建议不要调用该功能
        //		scanner.enablShowNoticeIcon(false);//是否允许显示iscan通知栏图标     部分设备 调用出现异常，建议不要调用该功能
        scanner.enableAddKeyValue(1);/**附加无、回车、Teble、换行*/
        scanner.timeOutSet(2);//设置扫描延时2秒
        scanner.intervalSet(10); //设置连续扫描间隔时间
        scanner.lightSet(false);//关闭右上角扫描指示灯
        scanner.enablePower(true);//省电模式
        //		scanner.addPrefix("AAA");//添加前缀
        //		scanner.addSuffix("BBB");//添加后缀
        //		scanner.interceptTrimleft(2); //截取条码左边字符
        //		scanner.interceptTrimright(3);//截取条码右边字符
        //		scanner.filterCharacter("R");//过滤特定字符
        //		scanner.SetErrorBroadCast(true);//扫描错误换行
        //      scanner.resultScan();//恢复iScan默认设置

        scanner.lockScanKey();
        //锁定设备的扫描按键,通过iScan定义扫描键扫描，用户也可以自定义按键。
//		scanner.unlockScanKey();
        //释放扫描按键的锁定，释放后iScan无法控制扫描按键，用户可自定义按键扫描。

        /**设置扫描结果的输出模式，参数为0和1：
         * 0为模拟输出（在光标停留的地方输出扫描结果）；
         * 1为广播输出（由应用程序编写广播接收者来获得扫描结果，并在指定的控件上显示扫描结果）
         * 这里采用接收扫描结果广播并在TextView中显示*/
        scanner.setOutputMode(1);

        //扫描结果的意图过滤器的动作一定要使用"android.intent.action.SCANRESULT"
        intentFilter = new IntentFilter(AppConfig.IDATA);
        //注册广播接受者
        scanReceiver = new ScannerResultReceiver();
        registerReceiver(scanReceiver, intentFilter);
    }

    /**
     * 结束扫描
     */
    private void finishScanner(){
        scanner.scan_stop();
        //    	 scanner.close();	//关闭iscan  非正常关闭会造成iScan异常退出
        try {
            unregisterReceiver(scanReceiver);	//反注册广播接收者
        } catch (IllegalArgumentException e) {

        }
        scanner.continceScan(false);
    }

    /**
     * 扫描结果的广播接收者
     */
    private class ScannerResultReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConfig.IDATA)){
                //获取扫描结果
                final String value = intent.getStringExtra("value");
                if(!value.equals(""))
                {
                    String code = "15"+value;
                    if(code.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_YX_RULE)))
//                    if(code.length()==10)
                    {
                        Map<String, String> params = new HashMap<>();
                        params.put("bagNo", code);
                        params.put("hisJobNum", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                        params.put("jobName", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGNAME));
                        params.put("receiveTime", StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
                        TelephonyManager telephonyManager = (TelephonyManager) aty
                                .getSystemService(Context.TELEPHONY_SERVICE);
                        params.put("setNo", telephonyManager.getDeviceId());
                        presenter.receiveBlood(params);
                    }
                }
            }
        }
    }

    @Override
    public void receiveBlood(CheckDataBean checkDataBean) {
        if (checkDataBean.getStatus().equals("200")) {
            ViewInject.toast("接血成功");
        } else {
            ViewInject.toast("接血失败");
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;

        }
    }
}
